package _interview100;

import java.util.Arrays;

/**
 * 56. 合并区间
 */
public class No56 {
    public int[][] merge(int[][] intervals) {
        int ansLen = 0;
        Arrays.sort(intervals, (o1, o2) -> o1[0] != o2[0] ? o1[0] - o2[0] : o2[1] - o1[1]);
        int[] curArr = new int[]{0, Integer.MIN_VALUE};
        for (int[] interval : intervals) {
            if (interval[1] <= curArr[1]) continue;
            else if (interval[0] <= curArr[1]) curArr[1] = interval[1];
            else {
                curArr = interval;
                intervals[ansLen++] = curArr;
            }
        }
        int[][] ans = new int[ansLen][2];
        System.arraycopy(intervals, 0, ans, 0, ansLen);
        return ans;
    }
}
